package org.jspresso.framework.application.frontend.action.entity;

import java.util.Map;
import java.util.Set;

import org.jspresso.framework.action.IActionHandler;
import org.jspresso.framework.application.frontend.action.FrontendAction;
import org.jspresso.framework.model.descriptor.IComponentDescriptor;
import org.jspresso.model.EntityDescriptor;
import org.jspresso.model.EntityDescriptorPicker;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ChooseEntityActionBase<E, F, G> extends FrontendAction<E, F, G> implements ApplicationContextAware {
	ApplicationContext applicationContext;
	Set<String> ecludedComponents;
	
	@Override
	public boolean execute(IActionHandler actionHandler, Map<String, Object> context) {

		EntityDescriptorPicker picker = getBackendController(context).getEntityFactory().createComponentInstance(EntityDescriptorPicker.class);
		for(IComponentDescriptor<?> componentDescriptor : getBackendController(context).getEntityFactory().getComponentDescriptors()) {
			if(componentDescriptor.getComponentContract().isInterface() && (ecludedComponents == null || !ecludedComponents.contains(componentDescriptor.getComponentContract().getCanonicalName()))) {
				EntityDescriptor entityDescriptor = getBackendController(context).getEntityFactory().createComponentInstance(EntityDescriptor.class);
				entityDescriptor.setDescriptor(componentDescriptor);
				picker.addToDescriptors(entityDescriptor);
			}
		}
		setActionParameter(picker, context);		
		return super.execute(actionHandler, context);
	}

	public void setEcludedComponents(Set<String> ecludedComponents) {
		this.ecludedComponents = ecludedComponents;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;;		
	}

}
